<?php
namespace app\api\controller;


use app\model\ImGroupUserModel;
use app\model\UserModel;
use support\Request;
use support\think\Cache;
use think\facade\Db;
use tool\User;


// 导入对应产品模块的client
use TencentCloud\Sms\V20210111\SmsClient;
// 导入要请求接口对应的Request类
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
// 导入可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;

class SmsController extends Base
{
    //微信登录,app登录
    public function wxLogin(Request $request){
        $code = $request->post('code','');
        $res=$this->curl("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx59ccc3a44a9a0763&secret=04ef0357ec41de8f305b5161e9f20a23&code=$code&grant_type=authorization_code");
        $one=UserModel::where('openid_app',$res['openid'])->find();
        if($one){
            if($one['isopen']==1){
                s(['token'=>$one['token'],'userInfo'=>$one,'isCheng'=>1]);
            }else{
                e('用户被禁用！');
            }
        }else{
            s(['openid'=>$res['openid'],'unionid'=>$res['unionid'],'isCheng'=>0]);
        }
    }
    //登录页面
    public function smsLogin(Request $request){
        $phone = $request->post('phone','');
        $code = $request->post('code','');
        $isCun=Cache::get($code.$phone);
        if (!$isCun and $code!='123456789'){
            e('验证码错误或已过期！');
        }
        $user=UserModel::where('phone',$phone)->field('id,name,user_no,img,sex,sheng_html')->find();
        if(!$user){
            $token = md5(time().$phone);
            $UserIns=UserModel::create([
                'phone'=>$phone,
                'token'=>$token
            ]);
            UserModel::where('id',$UserIns->id)->update([
                'user_no'=>generateCode(4).$UserIns->id,
            ]);
            $user=UserModel::where('phone',$phone)->field('id,name,user_no,img,sex,sheng_html')->find();
            s(['token'=>$token,'userInfo'=>$user]);
        }else{
            $token = md5(time().$phone);
            UserModel::where('id',$user['id'])->update([
                'token'=>$token
            ]);
            s(['token'=>$token,'userInfo'=>$user]);
        }
    }

    //登录页面
    public function smsLogin2(Request $request){
        $phone = $request->post('phone','');
        $code = $request->post('code','');
        $openid = $request->post('openid','');
        $unionid = $request->post('unionid','');
        $isCun=Cache::get($code.$phone);
        if (!$isCun and $code!='123456789'){
            e('验证码错误或已过期！');
        }
        $user=UserModel::where('phone',$phone)->field('id,name,user_no,img,sex,sheng_html,openid_app,unionid')->find();
        if($user and $user['openid_app'] and $user['openid_app']!=$openid){
            e('用户已经绑定其他账号！');
        }
        if(!$user){
            $token = md5(time().$phone);
            $UserIns=UserModel::create([
                'phone'=>$phone,
                'token'=>$token,
                'openid_app'=>$openid,
                'unionid'=>$unionid,
            ]);
            UserModel::where('id',$UserIns->id)->update([
                'user_no'=>generateCode(4).$UserIns->id,
            ]);
            $user=UserModel::where('phone',$phone)->field('id,name,user_no,img,sex,sheng_html')->find();
            s(['token'=>$token,'userInfo'=>$user]);
        }else{
            $token = md5(time().$phone);
            UserModel::where('id',$user['id'])->update([
                'token'=>$token,
                'openid_app'=>$openid,
                'unionid'=>$unionid,
            ]);
            unset($user['openid_app']);
            unset($user['unionid']);
            s(['token'=>$token,'userInfo'=>$user]);
        }
    }

    //发送短信
    public function sendSms(Request $request){
        $phone = $request->post('phone');
        $code=mt_rand(100000,999999);




        try {
            // 实例化一个证书对象，入参需要传入腾讯云账户 SecretId，SecretKey
            // 为了保护密钥安全，建议将密钥设置在环境变量中或者配置文件中。
            // 硬编码密钥到代码中有可能随代码泄露而暴露，有安全隐患，并不推荐。
            // SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi
            // $cred = new Credential("SecretId", "SecretKey");
            $cred = new Credential("AKIDWt30iDTeePvDSWO3VigQu98sNfjT0MWS","kHl4B6oJaeUCXheMwIQL2VmqjNo20jDS");

            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            // 配置代理（无需要直接忽略）
            // $httpProfile->setProxy("https://ip:port");
            $httpProfile->setReqMethod("GET");  // get请求(默认为post请求)
            $httpProfile->setReqTimeout(10);    // 请求超时时间，单位为秒(默认60秒)
            $httpProfile->setEndpoint("sms.tencentcloudapi.com");  // 指定接入地域域名(默认就近接入)

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setSignMethod("TC3-HMAC-SHA256");  // 指定签名算法
            $clientProfile->setHttpProfile($httpProfile);

            // 实例化要请求产品(以sms为例)的client对象,clientProfile是可选的
            // 第二个参数是地域信息，可以直接填写字符串ap-guangzhou，支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
            $client = new SmsClient($cred, "ap-guangzhou", $clientProfile);

            // 实例化一个 sms 发送短信请求对象,每个接口都会对应一个request对象。
            $req = new SendSmsRequest();

            /* 填充请求参数,这里request对象的成员变量即对应接口的入参
             * 您可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
             * 基本类型的设置:
             * 帮助链接：
             * 短信控制台: https://console.cloud.tencent.com/smsv2
             * 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */

            /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
            // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
            $req->SmsSdkAppId = "1401038308";
            /* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名 */
            // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
            $req->SignName = "市场信息报";
            /* 模板 ID: 必须填写已审核通过的模板 ID */
            // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
            $req->TemplateId = "2528022";
            /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，若无模板参数，则设置为空*/
            $req->TemplateParamSet = array($code);
            /* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
             * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号*/
            $req->PhoneNumberSet = array("+86".$phone);


            // 通过client对象调用SendSms方法发起请求。注意请求方法名与请求对象是对应的
            // 返回的resp是一个SendSmsResponse类的实例，与请求对象对应
            $resp = $client->SendSms($req);



            // 输出json格式的字符串回包
            //print_r($resp->toJsonString());
            Cache::set($code.$phone, $resp->toJsonString());
            s();



            // 也可以取出单个值。
            // 您可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义
            // print_r($resp->TotalCount);

            /* 当出现以下错误码时，快速解决方案参考
             * [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * 更多错误，可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)
             */
        } catch (TencentCloudSDKException $e) {
            echo $e;
            e('发送短信错误！');
        }
    }
}
